import { FC, useEffect, useMemo, useState } from "react";
import { observer, inject } from "mobx-react";
import {
  Typography,
  Select,
  Tooltip,
  Popconfirm,
  Row,
  Col,
  Popover,
  Table,
  Tabs,
  Form,
  Modal,
  Space,
  Button,
  message,
  Spin,
} from "antd";
import {
  EditOutlined,
  DeleteOutlined,
  CaretUpOutlined,
  CaretDownOutlined,
} from "@ant-design/icons";
import math, { FIXEDINDEX } from "../../utils/math";
import { ReagentPop } from "./BottlesPlane";
import { createList, ROWWORD, getReagentType } from "../../utils";

import ReactorChart from "./ReactorChart";
// import { getLastStep } from "../Designer/DesignerReactor";
import ReagentAmount from "../components/ReagentAmount";
import { ITStore } from "../../store";
import { ITShelf, ITReagent } from "../../store/interfaces";

import "./index.less";

interface TProp {
  store: ITStore;
}

interface ITReagentModalProp extends TProp {
  isShow: boolean;
  bottleName: string;
  close: () => void;
  emptyTubeList: string[];
}

type TReactorReagent = {
  label: string;
  value: string;
  amount?: number;
  mmol: number;
  weight: number;
  volume: number;
  type: number | undefined;
  unit: string;
};

interface TReactorReagentForm {
  reagentid: string;
  amount: number;
  mmol: number;
  weight: number;
  volume: number;
  from: any;
  step: number;
}

interface ITReactorReagentEditForm extends TReactorReagentForm {
  _id?: string;
  reactorid: string;
}

interface ITReactorReagentPop extends TProp {
  data: ITReactorReagentEditForm[];
  bottleName: string;
}

interface ITRRList extends TProp {
  editData?: any;
}

type TCopyReagent = {
  reagentid: string;
  mmol: number | null;
  weight: number | null;
  volume: number | null;
  type: number | undefined;
};

const { Link } = Typography;

const { Option } = Select;

const WRAPWIDE = 780;
const WRAPHEIGHT = 360;

export const useReactorReagents = ({
  store,
  editData,
}: ITRRList): TReactorReagent[] => {
  const {
    languageStore: { lang, langCur },
    designerStore: { reactorReagents, currentReagentsInfo },
    reagentStore: { getReagentInfoById, getReagentUnit },
  } = store;

  const [reactorReagentList, setReactorReagentList] = useState<
    TReactorReagent[]
  >([]);

  useEffect(() => {
    let tempReactReagentList: TReactorReagent[] = [];
    if (reactorReagents && reactorReagents.length) {
      reactorReagents.forEach((item) => {
        let { id, mmol, type, volume, weight } = item;
        const reagentInfo = getReagentInfoById(id);
        if (reagentInfo) {
          const { name, cnname } = reagentInfo;
          const unit = getReagentUnit(id, lang);
          let label = name;
          if (langCur === "zhcn") {
            label = cnname || name;
          }
          // 如果是编辑，则分数要加上编辑的数量
          if (editData && editData.reagentid === id) {
            if (mmol) {
              let tempMmol: any = math.format(
                math.evaluate(`${mmol} + ${editData.mmol}`),
                FIXEDINDEX
              );
              mmol = tempMmol - 0;
            }
            if (volume) {
              let tempVolume: any = math.format(
                math.evaluate(`${volume} + ${editData.volume}`),
                FIXEDINDEX
              );
              volume = tempVolume - 0;
            }
            if (weight) {
              let tempWeight: any = math.format(
                math.evaluate(`${weight} + ${editData.weight}`),
                FIXEDINDEX
              );
              weight = tempWeight - 0;
            }
          }

          tempReactReagentList.push({
            label,
            value: id,
            mmol,
            type,
            volume,
            weight,
            unit,
          });
        }
      });
    }
    setReactorReagentList(tempReactReagentList);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [currentReagentsInfo, editData]);
  return reactorReagentList;
};

// 试剂盘hover弹窗
const ReactorReagentTable: FC<ITReactorReagentPop | any> = inject("store")(
  observer(({ store, data, bottleName }: ITReactorReagentPop) => {
    const {
      languageStore: { lang, langCur },
      reagentStore: { getReagentInfoById },
      designerStore: {
        delDataReactorReagent,
        currentDesigner,
        changeEditReactorReagentData,
        changeShowReactorReagentDataModal,
        changeReactorStep,
        getDesignerInfo,
      },
    } = store;

    const [rendData, setRendData] = useState([]);

    const [stepLoading, setStepLoading] = useState(false);
    useEffect(() => {
      let tempList: any = [];

      if (data && data.length) {
        data.forEach((item, index) => {
          const {
            mmol,
            weight,
            volume,
            reagentid,
            _id,
            from,
            reactorid,
            step,
          } = item;
          const reagentInfo = getReagentInfoById(reagentid);
          if (reagentInfo) {
            const { name, cnname, type } = reagentInfo;
            const regType = getReagentType(type);
            let title = name;
            if (langCur === "zhcn") {
              title = cnname || name;
            }
            let showPrev = false;
            let showNext = false;

            if (data.length > 1) {
              if (index > 0) {
                showPrev = true;
              }
              if (index < data.length - 1) {
                showNext = true;
              }
            }

            tempList.push({
              key: index,
              title,
              mmol,
              weight,
              volume,
              reagentid,
              _id,
              from,
              reactorid,
              step,
              showPrev,
              showNext,
              regType,
            });
          }
        });
      }
      setRendData(tempList);
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [data]);

    const deleteItem = async (record: any) => {
      if (currentDesigner) {
        const { id } = currentDesigner;
        const { from } = record;
        await delDataReactorReagent({
          designerId: id,
          from,
        });
      }
    };

    const modifyItem = async (record: any) => {
      if (currentDesigner) {
        record.bottleName = bottleName;
        changeEditReactorReagentData(record);
        changeShowReactorReagentDataModal(true);
      }
    };

    // 向上移动
    const prevClick = async (curstep: number, idx: number) => {
      const { id } = currentDesigner || {};

      let nextStep = -1;
      let tempData: any = rendData[idx - 1];
      if (tempData) {
        nextStep = tempData?.step;
      }

      setStepLoading(true);
      await changeReactorStep({
        id,
        step: curstep,
        nextStep,
      });
      await getDesignerInfo({ id });
      setStepLoading(false);
    };

    // 向下移动
    const nextClick = async (curstep: number, idx: number) => {
      const { id } = currentDesigner || {};

      let nextStep = -1;
      let tempData: any = rendData[idx + 1];
      if (tempData) {
        nextStep = tempData?.step;
      }

      setStepLoading(true);
      await changeReactorStep({
        id,
        nextStep,
        step: curstep,
      });
      await getDesignerInfo({ id });
      setStepLoading(false);
    };

    const columns: any = [
      {
        title: lang["langname"],
        dataIndex: "title",
        key: "title",
        render: (txt: string, record: any) => {
          const { position, reagentid } = record;
          const reagentInfo = getReagentInfoById(reagentid);
          return (
            <Popover
              title={position}
              content={<ReagentPop reagentInfo={reagentInfo} />}
            >
              <Link>{txt}</Link>
            </Popover>
          );
        },
      },
      {
        title: lang["langamount"],
        dataIndex: "amount",
        key: "amount",
        render: (_amount: number, record: any) => {
          const { mmol, weight, volume, regType } = record;
          let tempAmount = null;
          let tempUnit = null;
          if (mmol) {
            tempAmount = mmol;
            tempUnit = lang["langmmol"];
          } else {
            if (regType === 1) {
              tempAmount = volume;
              tempUnit = lang["langmlunit"];
            } else if (regType === 2) {
              tempAmount = weight;
              tempUnit = lang["langmg"];
            }
          }

          if (tempAmount > 0) {
            return (
              <Popover
                title=""
                content={<ReagentAmount data={{ mmol, weight, volume }} />}
              >
                <Link>
                  {tempAmount}
                  {tempUnit}
                </Link>
              </Popover>
            );
          }
          return "";
        },
      },
      {
        title: lang["langedit"],
        dataIndex: "edit",
        key: "edit",
        width: 110,
        align: "center",
        render: (txt: string, record: any) => {
          return (
            <Space>
              <Tooltip title={lang["langedit"]}>
                <Button
                  type="link"
                  icon={<EditOutlined />}
                  onClick={() => {
                    modifyItem(record);
                  }}
                />
              </Tooltip>
              <Popconfirm
                title={lang["langconfirmdel"]}
                onConfirm={() => {
                  deleteItem(record);
                }}
              >
                <Tooltip title={lang["langdelete"]}>
                  <Button
                    type="link"
                    danger
                    // loading={delData?.id === record.id && delShelfLoading}
                    icon={<DeleteOutlined />}
                  />
                </Tooltip>
              </Popconfirm>
            </Space>
          );
        },
      },
      {
        title: lang["langstep"],
        dataIndex: "step",
        key: "step",
        render: (txt: number, record: any) => {
          const { showPrev, showNext, key } = record;
          return (
            <>
              {stepLoading && <Spin />}
              {!stepLoading && showPrev && (
                <CaretUpOutlined
                  style={{ color: "#1890ff", cursor: "pointer" }}
                  onClick={() => {
                    prevClick(txt, key);
                  }}
                />
              )}
              {!stepLoading && showNext && (
                <CaretDownOutlined
                  style={{ color: "#1890ff", cursor: "pointer" }}
                  onClick={() => {
                    nextClick(txt, key);
                  }}
                />
              )}
            </>
          );
        },
      },
    ];

    return (
      <Table dataSource={rendData} columns={columns} bordered size="small" />
    );
  })
);

// 新增，复制试剂信息弹窗
const ReactorReagentModal: FC<ITReagentModalProp | any> = inject("store")(
  observer(
    ({
      store,
      isShow,
      close,
      bottleName,
      emptyTubeList,
    }: ITReagentModalProp) => {
      const {
        languageStore: { lang, replaceLang, langCur },
        designerStore: {
          currentDesigner,
          currentReactorReagents,
          reactorReagentLoading,
          copyReactorReagent,
        },
        reagentStore: { getReagentInfoById },
      } = store;

      const [form] = Form.useForm();

      const [formcopy] = Form.useForm();

      const [curTab, setCurTab] = useState<string>("1");

      // 合并后的试剂信息
      const [reagentInfoList, setReagentInfoList] = useState<any>({});

      // 当无反应试剂时，禁用复制功能
      const [disabledCopy, setDisabledCopy] = useState(false);

      const [currentForm, setCurrentForm] = useState(form);

      const [selectReagentInfo, setSelectReagentInfo] =
        useState<ITReagent | null>(null);

      const closeModal = () => {
        currentForm.resetFields();
        setCurTab("1");
        setSelectReagentInfo(null);
        close();
      };

      const reatorReagentList = useReactorReagents({ store });

      const tabChange = (tab: string) => {
        setCurTab(tab);
        if (tab === "1") {
          formcopy.resetFields();
          setCurrentForm(form);
        } else if (tab === "2") {
          form.resetFields();
          setCurrentForm(formcopy);
        }
      };

      const onOk = () => {
        if (curTab === "1") {
          form.submit();
        } else if (curTab === "2") {
          formcopy.submit();
        }
      };

      // 复制实验步骤
      const reaginetCopyFinish = async (data: any) => {
        const { tubes } = data;
        const count = tubes.length;
        /**
         * 判断试剂是否足够
         */

        //找出被复制瓶的所有试剂, 然后乘以份数
        let regType = null;
        const copyReagents: TCopyReagent[] = [];
        currentReactorReagents.forEach((item) => {
          const { tubeName, reagentid, type, volume, weight, mmol } = item;
          if (tubeName === bottleName) {
            regType = type;
            let tempMmol: number | null = null;
            let tempVolume: number | null = null;
            let tempWeight: number | null = null;

            if (mmol !== null) {
              let temp: any = math.format(math.evaluate(`${mmol} * ${count}`));
              tempMmol = temp - 0;
            }

            if (volume !== null) {
              let temp: any = math.format(
                math.evaluate(`${volume} * ${count}`)
              );
              tempVolume = temp - 0;
            }

            if (weight !== null) {
              let temp: any = math.format(
                math.evaluate(`${weight} * ${count}`)
              );
              tempWeight = temp - 0;
            }
            copyReagents.push({
              mmol: tempMmol,
              weight: tempWeight,
              volume: tempVolume,
              reagentid,
              type,
            });
          }
        });

        // 找出缺少的试剂和计算缺少的份数
        const missingList: TCopyReagent[] = [];
        copyReagents.forEach(({ reagentid, mmol, weight, volume, type }) => {
          reatorReagentList.some((ritem) => {
            let tempAmount: any = null;
            if (ritem.type === 1) {
              tempAmount = ritem.volume;
            } else if (ritem.type === 2) {
              tempAmount = ritem.weight;
            }

            if (ritem.value === reagentid && tempAmount) {
              let residueAmount: any = null;
              let tempMmol = null;
              let tempVolume = null;
              let tempWeight = null;
              if (type === 1 && volume) {
                let temp: any = math.format(
                  math.evaluate(`${tempAmount} - ${volume}`),
                  FIXEDINDEX
                );
                residueAmount = temp - 0;
                tempVolume = temp - 0;
              } else if (type === 2 && weight) {
                let temp: any = math.format(
                  math.evaluate(`${tempAmount} - ${weight}`),
                  FIXEDINDEX
                );
                residueAmount = temp - 0;
                tempWeight = temp - 0;
              }
              if (mmol !== null) {
                let temp: any = math.format(
                  math.evaluate(`${tempAmount} - ${mmol}`),
                  FIXEDINDEX
                );
                tempMmol = temp - 0;
              }

              if (residueAmount < 0) {
                missingList.push({
                  reagentid,
                  mmol: tempMmol,
                  weight: tempWeight,
                  volume: tempVolume,
                  type,
                });
              }
              return true;
            }
            return false;
          });
        });

        if (missingList.length > 0) {
          let tempStr: string[] = [];
          missingList.forEach(({ mmol, weight, volume, type, reagentid }) => {
            const reagentInfo: ITReagent | null = getReagentInfoById(reagentid);
            let unit = "";
            let amount = null;
            if (type === 1) {
              amount = volume;
              unit = lang["langmlunit"];
            } else if (type === 2) {
              amount = weight;
              unit = lang["langmg"];
            }
            if (reagentInfo) {
              const { cnname, name } = reagentInfo;
              if (langCur === "en") {
                tempStr.push(`${name}:${amount}${unit}`);
              } else if (langCur === "zhcn") {
                tempStr.push(`${cnname}:${amount}${unit}`);
              }
            }
          });

          // 提示缺少试剂
          message.error(lang["langlackreagent"] + tempStr.join(";") + ".");
        } else {
          // 复制试剂瓶
          if (currentDesigner) {
            const { id } = currentDesigner;
            // let step = getLastStep(reagentInfoList);
            // await copyReactorReagent({
            //   designerId: id,
            //   tubeName: bottleName,
            //   tubes,
            //   step,
            //   type: regType,
            // });
            closeModal();
          }
        }
      };

      useEffect(() => {
        let tempObj: any = {};
        if (currentReactorReagents && currentReactorReagents.length) {
          currentReactorReagents.forEach((item) => {
            const {
              tubeName,
              reagentid,
              mmol,
              weight,
              volume,
              from,
              id,
              step,
            } = item;
            if (!tempObj[tubeName]) {
              tempObj[tubeName] = [];
            }
            tempObj[tubeName].push({
              reagentid,
              mmol,
              weight,
              volume,
              from,
              reactorid: id,
              step,
            });
          });
        }
        setReagentInfoList(tempObj);
      }, [currentReactorReagents]);

      useEffect(() => {
        let hasReagent = false;
        if (bottleName && !!reagentInfoList[bottleName]) {
          hasReagent = true;
        }
        setDisabledCopy(!hasReagent);
      }, [reagentInfoList, bottleName]);

      const CoypForm = () => {
        return (
          <Form
            name="copyreaginetForm"
            form={formcopy}
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 18 }}
            onFinish={reaginetCopyFinish}
          >
            <Form.Item
              label={replaceLang(lang["langcopyto"], bottleName)}
              name="tubes"
              rules={[{ required: true }]}
            >
              <Select
                mode="multiple"
                allowClear
                style={{ width: "100%" }}
                placeholder=""
                onChange={() => {}}
              >
                {emptyTubeList.map((item: string) => (
                  <Option key={item} value={item}>
                    {item}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Form>
        );
      };

      return (
        <Modal
          title={bottleName}
          open={isShow}
          onOk={onOk}
          onCancel={closeModal}
          destroyOnClose={true}
          width="50%"
          getContainer={false}
          forceRender
          confirmLoading={reactorReagentLoading}
        >
          <Row>
            <Col flex="320px" style={{ marginRight: 40 }}>
              <ReactorReagentTable
                bottleName={bottleName}
                data={reagentInfoList[bottleName]}
              />
            </Col>
            <Col flex="auto">
              <Tabs
                activeKey={curTab}
                onChange={tabChange}
                style={{ minWidth: 400 }}
                items={[
                  {
                    label: lang["langaddreagenttabname"],
                    key: "1",
                    // children: (
                    //   <AddReactorForm
                    //     bottleName={bottleName}
                    //     form={form}
                    //     close={closeModal}
                    //     reatorReagentList={reatorReagentList}
                    //     selectReagentInfo={selectReagentInfo}
                    //     setSelectReagentInfo={setSelectReagentInfo}
                    //     reagentInfoList={reagentInfoList}
                    //     editData={null}
                    //   />
                    // ),
                  },
                  {
                    label: lang["langduplicatereaction"],
                    key: "2",
                    children: <CoypForm />,
                    disabled: disabledCopy,
                  },
                ]}
              ></Tabs>
            </Col>
          </Row>
        </Modal>
      );
    }
  )
);

// const ReactorReagentModal: FC<ITReagentModalProp | any> = inject("store")(
//   observer(
//     ({
//       store,
//       isShow,
//       close,
//       bottleName,
//       emptyTubeList,
//     }: ITReagentModalProp) => {
//       const {
//         languageStore: { lang, replaceLang, langCur },
//         designerStore: {
//           currentDesigner,
//           addReactorReagent,
//           currentReactorReagents,
//           reactorReagentLoading,
//           copyReactorReagent,
//         },
//         reagentStore: { getReagentInfoById, getReagentUnit },
//       } = store;

//       const [form] = Form.useForm();

//       const [formcopy] = Form.useForm();

//       const [addonAfter, setAddonAfter] = useState<string>("");

//       const [amountMax, setamountMax] = useState<number>(99999);

//       const [curTab, setCurTab] = useState<string>("1");

//       // 合并后的试剂信息
//       const [reagentInfoList, setReagentInfoList] = useState<any>({});

//       // 当无反应试剂时，禁用复制功能
//       const [disabledCopy, setDisabledCopy] = useState(false);

//       const [currentForm, setCurrentForm] = useState(form);

//       // 没有选择试剂时禁止填写数量
//       const [displayInput, setDisplayInput] = useState<boolean>(true);

//       // 自动计算
//       const [autoCalculation, setAutoCalculation] = useState<boolean>(true);

//       const [mmolRequire, setMmolRequire] = useState<boolean>(true);

//       const [weightRequire, setWeightRequire] = useState<boolean>(true);

//       const [volumeRequire, setVolumeRequire] = useState<boolean>(true);

//       // 选择的试剂信息
//       const [selectReagentInfo, setSelectReagentInfo] =
//         useState<ITReagent | null>(null);

//       const closeModal = () => {
//         currentForm.resetFields();
//         setCurTab("1");
//         setAddonAfter("");
//         close();
//         setSelectReagentInfo(null);
//       };

//       const reatorReagentList = useReactorReagents({ store });

//       const onSelect = (id: string) => {
//         reatorReagentList.some(({ value, unit, amount }) => {
//           if (value === id) {
//             setAddonAfter(unit);
//             setamountMax(amount);
//             const reagentInfo = getReagentInfoById(value);
//             setSelectReagentInfo(reagentInfo);
//             return true;
//           }
//           return false;
//         });
//         form.setFieldsValue({
//           mmol: null,
//           weight: null,
//           volume: null,
//         });
//         setDisplayInput(false);
//       };

//       const tabChange = (tab: string) => {
//         setCurTab(tab);
//         if (tab === "1") {
//           formcopy.resetFields();
//           setCurrentForm(form);
//           setSelectReagentInfo(null);
//         } else if (tab === "2") {
//           form.resetFields();
//           setCurrentForm(formcopy);
//         }
//       };

//       const mmolChange = (data: number | null) => {
//         if (autoCalculation) {
//           if (data) {
//             const { weight, volume } = getAmountByMmol(data, selectReagentInfo);
//             if (weight && volume) {
//               form.setFieldsValue({
//                 weight,
//                 volume,
//               });
//             }
//           } else {
//             form.setFieldsValue({
//               weight: null,
//               volume: null,
//             });
//           }
//         }
//       };

//       const weightChange = (data: number | null) => {
//         if (autoCalculation) {
//           if (data) {
//             const { mmol, volume } = getAmountByWeight(data, selectReagentInfo);
//             form.setFieldsValue({
//               mmol,
//               volume,
//             });
//           } else {
//             form.setFieldsValue({
//               mmol: null,
//               volume: null,
//             });
//           }
//         }
//       };

//       const volumeChange = (data: number | null) => {
//         if (autoCalculation) {
//           if (data) {
//             const { mmol, weight } = getAmountByVolume(data, selectReagentInfo);
//             form.setFieldsValue({
//               mmol,
//               weight,
//             });
//           } else {
//             form.setFieldsValue({
//               mmol: null,
//               weight: null,
//             });
//           }
//         }
//       };

//       const onOk = () => {
//         if (curTab === "1") {
//           form.submit();
//         } else if (curTab === "2") {
//           formcopy.submit();
//         }
//       };

//       const reaginetFinish = async (data: TReactorReagentForm) => {
//         if (currentDesigner) {
//           let { id } = currentDesigner;
//           let step = getLastStep(reagentInfoList);
//           await addReactorReagent({
//             designerId: id,
//             data,
//             bottleName,
//             step: step + 1,
//           });
//           closeModal();
//         }
//       };

//       // 复制实验步骤
//       const reaginetCopyFinish = async (data: any) => {
//         const { tubes } = data;
//         const count = tubes.length;
//         /**
//          * 判断试剂是否足够
//          */

//         //找出被复制瓶的所有试剂, 然后乘以份数
//         const copyReagents: TCopyReagent[] = [];
//         currentReactorReagents.forEach(({ tubeName, amount, reagentid }) => {
//           if (tubeName === bottleName) {
//             copyReagents.push({
//               reagentid,
//               amount: amount * count,
//             });
//           }
//         });

//         // 找出缺少的试剂和计算缺少的份数
//         const missingList: TCopyReagent[] = [];
//         copyReagents.forEach(({ reagentid, amount }) => {
//           reatorReagentList.some((ritem) => {
//             if (ritem.value === reagentid) {
//               const residueAmount = ritem.amount - amount;
//               if (residueAmount < 0) {
//                 missingList.push({
//                   reagentid,
//                   amount: amount - ritem.amount,
//                 });
//               }
//               return true;
//             }
//             return false;
//           });
//         });

//         if (missingList.length > 0) {
//           let tempStr: string[] = [];
//           missingList.forEach(({ amount, reagentid }) => {
//             const reagentInfo: ITReagent | null = getReagentInfoById(reagentid);
//             const unit = getReagentUnit(reagentid, lang);
//             if (reagentInfo) {
//               const { cnname, name } = reagentInfo;
//               if (langCur === "en") {
//                 tempStr.push(`${name}:${amount}${unit}`);
//               } else if (langCur === "zhcn") {
//                 tempStr.push(`${cnname}:${amount}${unit}`);
//               }
//             }
//           });

//           // 提示缺少试剂
//           message.error(lang["langlackreagent"] + tempStr.join(";") + ".");
//         } else {
//           // 复制试剂瓶
//           if (currentDesigner) {
//             const { id } = currentDesigner;
//             let step = getLastStep(reagentInfoList);
//             await copyReactorReagent({
//               designerId: id,
//               tubeName: bottleName,
//               tubes,
//               step,
//             });
//             closeModal();
//           }
//         }
//       };

//       useEffect(() => {
//         let tempObj: any = {};
//         if (currentReactorReagents && currentReactorReagents.length) {
//           currentReactorReagents.forEach((item) => {
//             const { tubeName, reagentid, amount, from, id, step } = item;
//             if (!tempObj[tubeName]) {
//               tempObj[tubeName] = [];
//             }
//             tempObj[tubeName].push({
//               reagentid,
//               amount,
//               from,
//               reactorid: id,
//               step,
//             });
//           });
//         }
//         setReagentInfoList(tempObj);
//       }, [currentReactorReagents]);

//       useEffect(() => {
//         let hasReagent = false;
//         if (bottleName && !!reagentInfoList[bottleName]) {
//           hasReagent = true;
//         }
//         setDisabledCopy(!hasReagent);
//       }, [reagentInfoList, bottleName]);

//       useEffect(() => {
//         if (autoCalculation) {
//           setMmolRequire(true);
//           setWeightRequire(true);
//           setVolumeRequire(true);
//         } else {
//           if (!selectReagentInfo) {
//             setMmolRequire(false);
//             setWeightRequire(false);
//             setVolumeRequire(false);
//           } else {
//             const { type } = selectReagentInfo;
//             if (type === "tablet" || type === "powder") {
//               // 固体至少需要填写weight
//               setMmolRequire(false);
//               setWeightRequire(true);
//               setVolumeRequire(false);
//             } else if (type === "liquid" || type === "solution") {
//               // 液体至少需要填写volumn
//               setMmolRequire(false);
//               setWeightRequire(false);
//               setVolumeRequire(true);
//             } else {
//               setMmolRequire(false);
//               setWeightRequire(false);
//               setVolumeRequire(false);
//             }
//           }
//         }
//       }, [autoCalculation, selectReagentInfo]);

//       const switchChange = (checked: boolean) => {
//         setAutoCalculation(checked);
//       };

//       const AddForm = () => {
//         return (
//           <>
//             <Row style={{ marginBottom: 10 }}>
//               <Col span={24}>
//                 <Space style={{ float: "right" }}>
//                   {lang["langautocalc"]}
//                   <Switch checked={autoCalculation} onChange={switchChange} />
//                 </Space>
//               </Col>
//             </Row>

//             <Form
//               name="reaginetForm"
//               form={form}
//               labelCol={{ span: 6 }}
//               wrapperCol={{ span: 18 }}
//               onFinish={reaginetFinish}
//             >
//               <Form.Item
//                 label={
//                   <Space>
//                     {lang["langreagent"]}
//                     {!!selectReagentInfo ? (
//                       <Popover
//                         content={<ReagentPop reagentInfo={selectReagentInfo} />}
//                       >
//                         <InfoCircleOutlined />
//                       </Popover>
//                     ) : null}
//                   </Space>
//                 }
//                 name="reagentid"
//                 rules={[{ required: true }]}
//               >
//                 <Select optionLabelProp="label" onSelect={onSelect}>
//                   {reatorReagentList.map(({ value, label, amount, unit }) => {
//                     return (
//                       <Option key={value} label={label} disabled={false}>
//                         <div>
//                           <span style={{ float: "left" }}>{label}</span>
//                           <span style={{ float: "right" }}>
//                             {amount}
//                             {unit}
//                           </span>
//                         </div>
//                       </Option>
//                     );
//                   })}
//                 </Select>
//               </Form.Item>

//               <Form.Item
//                 label={lang["langMolaramout"]}
//                 name="mmol"
//                 rules={[{ required: mmolRequire }]}
//               >
//                 <InputNumber
//                   style={{ width: "100%" }}
//                   addonAfter={lang["langmmol"]}
//                   onChange={mmolChange}
//                   disabled={displayInput}
//                 />
//               </Form.Item>
//               <Form.Item
//                 label={lang["langweight"]}
//                 name="weight"
//                 rules={[{ required: weightRequire }]}
//               >
//                 <InputNumber
//                   style={{ width: "100%" }}
//                   addonAfter={lang["langmg"]}
//                   onChange={weightChange}
//                   disabled={displayInput}
//                 />
//               </Form.Item>
//               <Form.Item
//                 label={lang["langvolume"]}
//                 name="volume"
//                 rules={[{ required: volumeRequire }]}
//               >
//                 <InputNumber
//                   style={{ width: "100%" }}
//                   addonAfter={lang["langmlunit"]}
//                   onChange={volumeChange}
//                   disabled={displayInput}
//                 />
//               </Form.Item>
//             </Form>
//           </>
//         );
//       };

//       const CoypForm = () => {
//         return (
//           <Form
//             name="copyreaginetForm"
//             form={formcopy}
//             labelCol={{ span: 6 }}
//             wrapperCol={{ span: 18 }}
//             onFinish={reaginetCopyFinish}
//           >
//             <Form.Item
//               label={replaceLang(lang["langcopyto"], bottleName)}
//               name="tubes"
//               rules={[{ required: true }]}
//             >
//               <Select
//                 mode="multiple"
//                 allowClear
//                 style={{ width: "100%" }}
//                 placeholder=""
//                 onChange={() => { }}
//               >
//                 {emptyTubeList.map((item: string) => (
//                   <Option key={item} value={item}>
//                     {item}
//                   </Option>
//                 ))}
//               </Select>
//             </Form.Item>
//           </Form>
//         );
//       };

//       return (
//         <Modal
//           title={bottleName}
//           open={isShow}
//           onOk={onOk}
//           onCancel={closeModal}
//           destroyOnClose={true}
//           width="50%"
//           getContainer={false}
//           forceRender
//           confirmLoading={reactorReagentLoading}
//         >
//           <Row>
//             <Col flex="320px" style={{ marginRight: 40 }}>
//               <ReactorReagentTable
//                 bottleName={bottleName}
//                 data={reagentInfoList[bottleName]}
//               />
//             </Col>
//             <Col flex="auto">
//               <Tabs
//                 activeKey={curTab}
//                 onChange={tabChange}
//                 style={{ minWidth: 400 }}
//                 items={[
//                   {
//                     label: lang["langaddreagenttabname"],
//                     key: "1",
//                     children: <AddForm />,
//                   },
//                   {
//                     label: lang["langduplicatereaction"],
//                     key: "2",
//                     children: <CoypForm />,
//                   },
//                 ]}
//               ></Tabs>
//             </Col>
//           </Row>
//         </Modal>
//       );
//     }
//   )
// );

const ReactorPanel: FC<TProp | any> = ({ store }: TProp): JSX.Element => {
  const {
    languageStore: { lang },
    designerStore: {
      currentDesigner,
      currentReactorReagents,
      reactorReagentLoading,
      clearReactorReagen,
    },
    shelfStore: { allShelf },
  } = store;

  const [curReactorShelf, setCurReactorShelf] = useState<ITShelf | null>(null);

  const [rowList, setRowList] = useState<number[]>([]);

  const [colList, setColList] = useState<number[]>([]);

  const [bottlediameter, setBottlediameter] = useState<number>(0);

  const [rowMarg, setRowMarg] = useState<number>(0);

  const [showReagentModal, setShowReagentModal] = useState<boolean>(false);

  const [modalBottleName, setModalBottleName] = useState<string>("");

  // 合并后的试剂信息
  const [reagentInfoList, setReagentInfoList] = useState<any>({});

  // 获取反应架
  useEffect(() => {
    if (currentDesigner && allShelf.length) {
      const reactorSlotShelf: any = currentDesigner.reactorSlotShelf;
      const reactorSlots = Object.keys(reactorSlotShelf) || [];
      const slotName = reactorSlots[0];
      if (slotName) {
        const { shelf } = reactorSlotShelf[slotName];
        if (shelf) {
          allShelf.some((item: ITShelf) => {
            if (item.name === shelf) {
              setCurReactorShelf(item);
              return true;
            }
            return false;
          });
        }
      }
    }
  }, [currentDesigner, allShelf]);

  useEffect(() => {
    let tempObj: any = {};
    if (currentReactorReagents && currentReactorReagents.length) {
      currentReactorReagents.forEach((item) => {
        const {
          tubeName,
          reagentid,
          mmol,
          weight,
          volume,
          from,
          id,
          step,
          type,
        } = item;
        if (!tempObj[tubeName]) {
          tempObj[tubeName] = [];
        }
        tempObj[tubeName].push({
          reagentid,
          mmol,
          weight,
          volume,
          from,
          reactorid: id,
          step,
          type,
        });
      });
    }
    setReagentInfoList(tempObj);
  }, [currentReactorReagents]);

  useEffect(() => {
    if (curReactorShelf) {
      const { length, row, column, bottleList } = curReactorShelf;

      let diameter: any = 0;

      if (bottleList) {
        diameter = bottleList[0].diameter;
      }

      let planeRate = WRAPWIDE / length;

      setRowList(createList(row || 0));

      setColList(createList(column || 0));

      setBottlediameter(Math.floor(planeRate * diameter) || 0);

      setRowMarg(Math.floor((WRAPHEIGHT - diameter * row) / (2 * row)) || 0);
    }
  }, [curReactorShelf]);

  // 计算空试剂瓶列表
  const emptyTubeList: string[] = useMemo(() => {
    let list: string[] = [];
    rowList.forEach((item: number) => {
      const rowName = ROWWORD[item];
      colList.forEach((cItem: number) => {
        const bottleName = rowName + (cItem + 1);
        const reagentInfos = reagentInfoList[bottleName];
        if (!reagentInfos) {
          list.push(bottleName);
        }
      });
    });
    return list;
  }, [rowList, colList, reagentInfoList]);

  const bottleClick = (bottleName: string) => {
    setModalBottleName(bottleName);
    setShowReagentModal(true);
  };

  const closeReagentModal = () => {
    setShowReagentModal(false);
  };

  // const closeEditReagentModal = () => {
  //   setShowEditReagentModal(true);
  // };

  const clearAll = async (bottleName: string) => {
    if (
      currentReactorReagents &&
      currentReactorReagents.length &&
      currentDesigner
    ) {
      const { id } = currentDesigner;
      await clearReactorReagen({
        designerId: id,
        tubeName: bottleName,
      });
    }
  };

  return (
    <>
      <div className="reactorplane" style={{ width: WRAPWIDE }}>
        {rowList.map((item: number) => {
          const rowName = ROWWORD[item];
          return (
            <div
              key={item}
              className="row"
              style={{ marginTop: rowMarg, marginBottom: rowMarg }}
            >
              {colList.map((cItem: number) => {
                const bottleName = rowName + (cItem + 1);
                const reagentInfos = reagentInfoList[bottleName];
                const hasData = !!reagentInfos;

                return (
                  <Popover
                    title={
                      hasData && (
                        <Row>
                          <Col span={12} style={{ fontSize: 18 }}>
                            {bottleName}
                          </Col>
                          <Col span={12}>
                            <Button
                              type="primary"
                              danger
                              style={{ float: "right" }}
                              onClick={() => {
                                clearAll(bottleName);
                              }}
                              loading={reactorReagentLoading}
                            >
                              {lang["langclear"]}
                            </Button>
                          </Col>
                        </Row>
                      )
                    }
                    content={
                      hasData && (
                        <ReactorReagentTable
                          bottleName={bottleName}
                          data={reagentInfos}
                        />
                      )
                    }
                    key={cItem}
                  >
                    <div
                      className="col"
                      style={{
                        width: bottlediameter,
                        height: bottlediameter,
                      }}
                      onClick={() => {
                        bottleClick(bottleName);
                      }}
                    >
                      <div className="rchar">
                        <ReactorChart
                          height={bottlediameter}
                          data={reagentInfos}
                        />
                      </div>
                      <div
                        className="labelname"
                        style={{
                          lineHeight: `${bottlediameter}px`,
                        }}
                      >
                        {bottleName}
                      </div>
                    </div>
                  </Popover>
                );
              })}
            </div>
          );
        })}
      </div>

      {/* 添加反应试剂弹窗 */}
      <ReactorReagentModal
        isShow={showReagentModal}
        close={closeReagentModal}
        bottleName={modalBottleName}
        emptyTubeList={emptyTubeList}
      />
    </>
  );
};

export default inject("store")(observer(ReactorPanel));
